import getDeviceInfo from './deviceInfo'
import router from '../router'
import { urlDelP } from './utils'
import qs from 'qs'
import store from '../store'
import * as events from '../store/events'

let baseUrl = process.env.VUE_APP_BASE_URL
let appId = process.env.VUE_APP_ID
axios.defaults.withCredentials = true

export const isLogin = () => {
  if (!Cookies.get('czt_openinfo')) {
    // 没有登陆
    store.commit(events.CHANGE_USER_INFO, {})
  } else {
    // 有登陆信息的，重新获取个人信息
    store.dispatch('getUserInfo')
  }
}

export const wxLogin = () => {
  let state = window.getUrlParam('state')
  let code = window.getUrlParam('code')
  return new Promise((resolve, reject) => {
    // 不是手机端微信浏览器 直接返回
    if (!(getDeviceInfo().isWeiXin && getDeviceInfo().isPhone)) {
      resolve()
      return
    }
    if (code) {
      axios
        .post(
          baseUrl + '/interface/mobile/account.php',
          qs.stringify({
            action: 'wechat_login',
            code: code,
            state: state,
          })
        )
        .then((data) => {
          let status = parseInt(data.data.status)
          if (status === 1) {
            // 每次登陆清理个人中心 和 我的名片 浮窗
            window.localStorage.removeItem('cardFloat')
            window.localStorage.removeItem('centerFloat')
            // 成功
            resolve()
          } else if (status === 10000) {
            // 登录过期
            Cookies.remove('czt_openinfo', {
              path: '/',
              domain: process.env.VUE_APP_COOKIE_DOMAIN,
            })
            store.commit(events.CHANGE_USER_INFO, {})
            router.push('/login')
            reject()
          } else if (status === 10020) {
            // code失效
            reject()
            // 去除 code
            let nowPageUrl = urlDelP(window.location.href, 'code')
            redirectWX(nowPageUrl)
          } else {
            reject()
          }
        })
        .catch((err) => {
          console.log(err)
          reject()
        })
    } else {
      reject()
      redirectWX(window.location.href)
    }
  })
}

export const bindWx = () => {
  let state = window.getUrlParam('state')
  let code = window.getUrlParam('code')
  return new Promise((resolve, reject) => {
    // 不是手机端微信浏览器 直接返回
    if (!(getDeviceInfo().isWeiXin && getDeviceInfo().isPhone)) {
      resolve()
      return
    }
    if (code) {
      axios
        .post(
          baseUrl + '/interface/mobile/personal.php',
          qs.stringify({
            action: 'bind_wechat',
            code: code,
            state: state,
          })
        )
        .then((data) => {
          let status = parseInt(data.data.status)
          if (status === 1) {
            store.dispatch('getUserInfo')
            // 成功
            resolve(data)
          } else if (status === 10000) {
            // 登录过期
            Cookies.remove('czt_openinfo', {
              path: '/',
              domain: process.env.VUE_APP_COOKIE_DOMAIN,
            })
            store.commit(events.CHANGE_USER_INFO, {})
            router.push('/login')
            reject()
          } else if (status === 20020) {
            // code失效
            reject()
            // 去除 code
            let nowPageUrl = urlDelP(window.location.href, 'code')
            redirectWX(nowPageUrl, 'auth')
          } else if (status === 20021) {
            // 该微信已被绑定了
            resolve(data)
          } else {
            reject(data)
          }
        })
        .catch((err) => {
          console.log(err)
          reject(data)
        })
    } else {
      reject()
      redirectWX(window.location.href, 'auth')
    }
  })
}

function redirectWX(urlp, auth) {
  let state = 'wechat_login'
  if (auth) {
    state = 'wechat_auth'
  }
  let url =
    'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
    appId +
    '&redirect_uri=' +
    encodeURIComponent(urlp) +
    '&response_type=code&scope=snsapi_userinfo&state=' +
    state +
    '#wechat_redirect'
  window.location.replace(url)
}
